package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.DocTypeAdapter;
import flc.ast.bean.MyDocTypeBean;
import flc.ast.databinding.ActivityCameraBinding;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class CameraActivity extends BaseAc<ActivityCameraBinding> {

    //相机设置
    private boolean isFlash = false;//判断是否打开闪光灯
    private DocTypeAdapter typeAdapter;
    private int oldPosition;

    @Override
    protected int onCreate() {
        return R.layout.activity_camera;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCameraBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivCameraStart.setOnClickListener(this);
        mDataBinding.ivCameraFlash.setOnClickListener(this);
        mDataBinding.ivCameraReversal.setOnClickListener(this);
        mDataBinding.ivCameraPicture.setOnClickListener(this);
        mDataBinding.tvCameraDoc.setOnClickListener(this);
        mDataBinding.tvCameraSingle.setOnClickListener(this);

        mDataBinding.rvDocTypeList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        typeAdapter = new DocTypeAdapter();
        mDataBinding.rvDocTypeList.setAdapter(typeAdapter);
        typeAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivCameraStart://开始拍摄
                if (mDataBinding.cameraView.isTakingPicture()) return;
                mDataBinding.cameraView.takePictureSnapshot();
                break;
            case R.id.ivCameraReversal://镜头反转
                reversalLens();
                break;
            case R.id.ivCameraFlash://闪光灯
                openFlash();
                break;
            case R.id.ivCameraPicture://相册选择
                AlbumSelActivity.type = 5;
                startActivity(AlbumSelActivity.class);
                break;
            case R.id.tvCameraDoc://证件拍摄
                mDataBinding.tvCameraDoc.setVisibility(View.INVISIBLE);
                mDataBinding.tvCameraSingle.setVisibility(View.VISIBLE);
                mDataBinding.tvCameraType.setText(getString(R.string.doc_shot));
                mDataBinding.ivCameraIcon.setVisibility(View.VISIBLE);
                mDataBinding.llDocType.setVisibility(View.VISIBLE);
                break;
            case R.id.tvCameraSingle://单张拍摄
                mDataBinding.tvCameraDoc.setVisibility(View.VISIBLE);
                mDataBinding.tvCameraSingle.setVisibility(View.INVISIBLE);
                mDataBinding.tvCameraType.setText(getString(R.string.single_shot));
                mDataBinding.ivCameraIcon.setVisibility(View.GONE);
                mDataBinding.llDocType.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        typeAdapter.getItem(oldPosition).setSelected(false);
        typeAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        typeAdapter.getItem(position).setSelected(true);
        typeAdapter.notifyItemChanged(position);
        mDataBinding.ivCameraIcon.setImageResource(typeAdapter.getItem(position).getIcon());
    }

    @Override
    protected void initData() {
        getPermission();
        String[] type = getResources().getStringArray(R.array.doc_type_arr);
        List<MyDocTypeBean> listType = new ArrayList<>();
        listType.add(new MyDocTypeBean(type[0], R.drawable.ashengfzzhenm, true));
        listType.add(new MyDocTypeBean(type[1], R.drawable.ahukoub, false));
        listType.add(new MyDocTypeBean(type[2], R.drawable.ayinhangk, false));
        listType.add(new MyDocTypeBean(type[3], R.drawable.ahuzhao, false));
        listType.add(new MyDocTypeBean(type[4], R.drawable.axueshenz, false));
        listType.add(new MyDocTypeBean(type[5], R.drawable.asiliujizhengshu, false));
        listType.add(new MyDocTypeBean(type[6], R.drawable.afangchanz, false));
        typeAdapter.setList(listType);
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {

            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                int width = result.getSize().getWidth();
                int height = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (width * height > screenWidth * screenHeight) {
                    width = screenWidth;
                    height = screenHeight;
                }
                result.toBitmap(width, height, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        ClipsFileActivity.mImgBitmap = bitmap;
                        startActivity(ClipsFileActivity.class);
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {

            }

            @Override
            public void onVideoRecordingEnd() {

            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {

            }
        });
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.ashoudiantguan);
            mDataBinding.tvCameraFlash.setText(getString(R.string.flash_close));
            mDataBinding.cameraView.setFlash(Flash.OFF);
        } else {
            isFlash = true;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.ashoudiantkai);
            mDataBinding.tvCameraFlash.setText(getString(R.string.flash_open));
            mDataBinding.cameraView.setFlash(Flash.TORCH);
        }
    }

    //反转镜头
    private void reversalLens() {
        Facing curFacing = mDataBinding.cameraView.getFacing();
        if (curFacing == Facing.BACK) {
            mDataBinding.cameraView.setFacing(Facing.FRONT);
            mDataBinding.ivCameraReversal.setImageResource(R.drawable.ayifanzhuan);
        } else {
            mDataBinding.cameraView.setFacing(Facing.BACK);
            mDataBinding.ivCameraReversal.setImageResource(R.drawable.afanzhuanxiangji);
        }
    }

}